package com.tofch.biproject.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofch.biproject.annotation.AuthCheck;
import com.tofch.biproject.common.BaseResponse;
import com.tofch.biproject.common.DeleteRequest;
import com.tofch.biproject.common.ErrorCode;
import com.tofch.biproject.common.ResultUtils;
import com.tofch.biproject.constant.AIConstant;
import com.tofch.biproject.constant.CommonConstant;
import com.tofch.biproject.constant.UserConstant;
import com.tofch.biproject.exception.BusinessException;
import com.tofch.biproject.exception.ThrowUtils;
import com.tofch.biproject.manager.AiManager;
import com.tofch.biproject.manager.RedisLimiterManager;
import com.tofch.biproject.model.dto.chart.ChartAddRequest;
import com.tofch.biproject.model.dto.chart.ChartQueryRequest;
import com.tofch.biproject.model.dto.chart.ChartUpdateRequest;
import com.tofch.biproject.model.dto.chart.GenChartByAiRequest;
import com.tofch.biproject.model.entity.Chart;
import com.tofch.biproject.model.entity.User;
import com.tofch.biproject.model.vo.BiResponse;
import com.tofch.biproject.mq.BiMessageProucer;
import com.tofch.biproject.service.ChartService;
import com.tofch.biproject.service.UserService;
import com.tofch.biproject.utils.ExcelUtils;
import com.tofch.biproject.utils.SqlUtils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;


/**
 * 帖子接口
 *
 * @author tofch
 * @from https://gitee.com/tofch/bi-backend
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    @Resource
    private AiManager aiManager;

    @Resource
    private RedisLimiterManager redisLimiterManager;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private BiMessageProucer biMessageProucer;

    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);
        log.info("chart:{}", chart);

        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());

        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newChartId = chart.getId();
        return ResultUtils.success(newChartId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);


        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<Chart> getChartVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chart);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param chartQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        log.info("信息:{}", chartPage);
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<Chart>> listChartVOByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                       HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 获取查询包装类
     *
     * @param chartQueryRequest
     * @return
     */

    private QueryWrapper<Chart> getQueryWrapper(ChartQueryRequest chartQueryRequest) {
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        if (chartQueryRequest == null) {
            return queryWrapper;
        }


        Long id = chartQueryRequest.getId();

        String goal = chartQueryRequest.getGoal();
        String chartType = chartQueryRequest.getChartType();
        Long userId = chartQueryRequest.getUserId();
        String sortField = chartQueryRequest.getSortField();
        String sortOrder = chartQueryRequest.getSortOrder();

        // 拼接查询条件


        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(goal), "goal", goal);
        queryWrapper.eq(StringUtils.isNotBlank(chartType), "chartType", chartType);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq("isDelete", false);

        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }


    @PostMapping("/gen")
    public BaseResponse<BiResponse> genchartByAi(@RequestPart("file") MultipartFile multipartFile,
                                                 GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {

        String name = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();

        //文件检验文件类型与大小
        //获取
        String filename = multipartFile.getOriginalFilename();
        String suffix = FileUtil.getSuffix(filename);
        long size = multipartFile.getSize();

        final long ONE_MB = 1024 * 1024L;

        ThrowUtils.throwIf(size > ONE_MB, ErrorCode.PARAMS_ERROR, "文件过大");

        final List<String> validFileSuffixList = Arrays.asList("xlsx", "csv");

        ThrowUtils.throwIf(!validFileSuffixList.contains(suffix), ErrorCode.PARAMS_ERROR, "文件类型错误");
        log.info("request{}", request.getSession().getAttribute("USER_LOGIN_STATE"));

        //获取当前用户信息
        User loginUser = userService.getLoginUser(request);

        //校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标未空");
        ThrowUtils.throwIf(StringUtils.isBlank(name) || name.length() > 100, ErrorCode.PARAMS_ERROR, "名字不合格");

        //限流判断
        redisLimiterManager.doRateLimit(String.valueOf(loginUser.getId()));


//        final String promt = "你是一个数据分析师和前端开发专家，接下来我会按照以下固定格式给你提供内容: \n"+
//                "分析需求: \n" +
//                "{数据分析的需求或者目标} \n"+
//                "原始数据: \n"+
//                "{csv格式的原始数据,用,作为分隔符} \n"+
//                "请根据这两部分内容，按照以下指定格式生成内容(此外不要输出任何多余的开头、结尾、注释} \n"+
//                "【【【【【\n"+
//                "{前端 Echart V5 的option 配置对象Js代码，合理地将数据进行可视化，不要生成任何多余的内容，比如注释} \n"+
//                "【【【【【 \n";
        //用户输入目标
        StringBuilder userInput = new StringBuilder();

        userInput.append("需求分析：").append(goal).append("\n");

        userInput.append("图表类型：").append(chartType).append("\n");
        //压缩后的数据
        String result = ExcelUtils.excelToCsv(multipartFile);
        userInput.append("原始数据：").append(result).append("\n");

        String userInputResut = userInput.toString();

        long biModeId = 1768537411459436545L;


        //调用AI
        String endtResult = aiManager.doChart(userInputResut, biModeId);

        String[] splits = endtResult.split("【【【【【");

        if (splits.length < 2) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "AI 生成错误");
        }
        String genChart = splits[1].trim();
        String genResult = splits[2].trim();


        Chart chart = new Chart();

        chart.setGoal(goal);
        chart.setChartData(result);
        chart.setChartType(chartType);
        chart.setGenChart(genChart);
        chart.setGenResult(genResult);

//        Object  object= request.getSession().getAttribute(USER_LOGIN_STATE);
//        User user = (User) object;
//
        chart.setUserId(loginUser.getId());


        boolean save = chartService.save(chart);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "图表存储失败");

        BiResponse b = new BiResponse();
        b.setGenResult(genResult);
        b.setGenChart(genChart);
        b.setChartId(chart.getId());


        return ResultUtils.success(b);


    }

    @PostMapping("/genAys")
    public BaseResponse<BiResponse> genchartByAiAys(@RequestPart("file") MultipartFile multipartFile,
                                                    GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {

        String name = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();

        //文件检验文件类型与大小
        //获取
        String filename = multipartFile.getOriginalFilename();
        String suffix = FileUtil.getSuffix(filename);
        long size = multipartFile.getSize();

        final long ONE_MB = 1024 * 1024L;

        ThrowUtils.throwIf(size > ONE_MB, ErrorCode.PARAMS_ERROR, "文件过大");

        final List<String> validFileSuffixList = Arrays.asList("xlsx", "csv");

        ThrowUtils.throwIf(!validFileSuffixList.contains(suffix), ErrorCode.PARAMS_ERROR, "文件类型错误");
        log.info("request{}", request.getSession().getAttribute("USER_LOGIN_STATE"));

        //获取当前用户信息
        User loginUser = userService.getLoginUser(request);

        //校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标未空");
        ThrowUtils.throwIf(StringUtils.isBlank(name) || name.length() > 100, ErrorCode.PARAMS_ERROR, "名字不合格");

        //限流判断
        redisLimiterManager.doRateLimit(String.valueOf(loginUser.getId()));


//        final String promt = "你是一个数据分析师和前端开发专家，接下来我会按照以下固定格式给你提供内容: \n"+
//                "分析需求: \n" +
//                "{数据分析的需求或者目标} \n"+
//                "原始数据: \n"+
//                "{csv格式的原始数据,用,作为分隔符} \n"+
//                "请根据这两部分内容，按照以下指定格式生成内容(此外不要输出任何多余的开头、结尾、注释} \n"+
//                "【【【【【\n"+
//                "{前端 Echart V5 的option 配置对象Js代码，合理地将数据进行可视化，不要生成任何多余的内容，比如注释} \n"+
//                "【【【【【 \n";
        //用户输入目标
        StringBuilder userInput = new StringBuilder();

        userInput.append("需求分析：").append(goal).append("\n");

        userInput.append("图表类型：").append(chartType).append("\n");
        //压缩后的数据
        String result = ExcelUtils.excelToCsv(multipartFile);
        userInput.append("原始数据：").append(result).append("\n");

        String userInputResut = userInput.toString();


        Chart chart = new Chart();

        chart.setGoal(goal);
        chart.setChartData(result);
        chart.setChartType(chartType);
//
        chart.setUserId(loginUser.getId());


        boolean save = chartService.save(chart);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "图表存储失败");

        // todo 处理队列满之后，抛出异常
        CompletableFuture.runAsync(() -> {
            //调用AI
            //先修改图表任务状态为执行中，等执行完成后修改为”succeed,保存结果，失败抛异常，记录错误信息
            Chart updateChart = new Chart();
            updateChart.setId(chart.getId());
            updateChart.setStatus("running");
            boolean b = chartService.updateById(updateChart);
            if (!b) {
                handleChartUpdateError(chart.getId(), "图表状态更新失败");
                return;
            }


            String endtResult = aiManager.doChart(userInputResut, AIConstant.biModeId);

            String[] splits = endtResult.split("【【【【【");

            if (splits.length < 2) {
                handleChartUpdateError(chart.getId(), "AI 生成错误");
                return;
            }
            String genChart = splits[1].trim().replace("'", "\"");
            String genResult = splits[2].trim();

            Chart updateChartResult = new Chart();
            updateChartResult.setId(chart.getId());
            updateChartResult.setGenChart(genChart);
            updateChartResult.setGenResult(genResult);

            updateChartResult.setStatus("succeed");
            boolean b1 = chartService.updateById(updateChartResult);
            if (!b1) {
                handleChartUpdateError(chart.getId(), "AI 生成错误");
                return;
            }

        }, threadPoolExecutor);


        /**
         * 返回生成的chart 信息
         */
        BiResponse b = new BiResponse();
        b.setChartId(chart.getId());
        return ResultUtils.success(b);


    }

    private void handleChartUpdateError(long chartId, String execMessage) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus("failed");
        updateChartResult.setExecMessage(execMessage);
        chartService.updateById(updateChartResult);

    }

    /**
     * 异步请求加rabbitmq
     *
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */

    @PostMapping("/genAys/mq")
    public BaseResponse<BiResponse> genchartByAiAysMq(@RequestPart("file") MultipartFile multipartFile,
                                                      GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {

        String name = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();

        //文件检验文件类型与大小
        //获取
        String filename = multipartFile.getOriginalFilename();
        String suffix = FileUtil.getSuffix(filename);
        long size = multipartFile.getSize();

        final long ONE_MB = 1024 * 1024L;

        ThrowUtils.throwIf(size > ONE_MB, ErrorCode.PARAMS_ERROR, "文件过大");

        final List<String> validFileSuffixList = Arrays.asList("xlsx", "csv");

        ThrowUtils.throwIf(!validFileSuffixList.contains(suffix), ErrorCode.PARAMS_ERROR, "文件类型错误");
        log.info("request{}", request.getSession().getAttribute("USER_LOGIN_STATE"));

        //获取当前用户信息
        User loginUser = userService.getLoginUser(request);

        //校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标未空");
        ThrowUtils.throwIf(StringUtils.isBlank(name) || name.length() > 100, ErrorCode.PARAMS_ERROR, "名字不合格");

        //限流判断
        redisLimiterManager.doRateLimit(String.valueOf(loginUser.getId()));


//        final String promt = "你是一个数据分析师和前端开发专家，接下来我会按照以下固定格式给你提供内容: \n"+
//                "分析需求: \n" +
//                "{数据分析的需求或者目标} \n"+
//                "原始数据: \n"+
//                "{csv格式的原始数据,用,作为分隔符} \n"+
//                "请根据这两部分内容，按照以下指定格式生成内容(此外不要输出任何多余的开头、结尾、注释} \n"+
//                "【【【【【\n"+
//                "{前端 Echart V5 的option 配置对象Js代码，合理地将数据进行可视化，不要生成任何多余的内容，比如注释} \n"+
//                "【【【【【 \n";
        //用户输入目标
        StringBuilder userInput = new StringBuilder();

        userInput.append("需求分析：").append(goal).append("\n");

        userInput.append("图表类型：").append(chartType).append("\n");
        //压缩后的数据
        String result = ExcelUtils.excelToCsv(multipartFile);
        userInput.append("原始数据：").append(result).append("\n");

        String userInputResut = userInput.toString();



        Chart chart = new Chart();

        chart.setGoal(goal);
        chart.setChartData(result);
        chart.setChartType(chartType);

        chart.setUserId(loginUser.getId());

        //文件存在成功
        boolean save = chartService.save(chart);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "图表存储失败");

        long newChartId = chart.getId();

        //发送获取消息
        biMessageProucer.sendMessage(String.valueOf(newChartId));

        /**
         * 返回生成的chart 信息
         */
        BiResponse b = new BiResponse();
        b.setChartId(chart.getId());
        return ResultUtils.success(b);


    }


}
